package com.alex.projects.bitcask;

import static com.alex.projects.bitcask.core.StoreService.FILE_PREFIX;

public class Tools {

    public static short bytesToShort(byte[] content) {
        if (content.length > 2) {
            throw new RuntimeException("short must be 2 bytes");
        }
        short ret = content[0];
        ret = (short) (ret << 8);
        ret = (short) (ret | (0x00FF & content[1]));
        return ret;
    }

    public static int bytesToInt(byte[] content) {
        if (content.length > 4) {
            throw new RuntimeException("int must be 4 bytes");
        }
        int ret = content[0];
        ret = (ret << 24);
        ret = (ret | (0x000000FF & content[1]) << 16);
        ret = (ret | (0x000000FF & content[2]) << 8);
        ret = (ret | (0x000000FF & content[3]));
        return ret;
    }

    public static long bytesToLong(byte[] content) {
        if (content.length > 8) {
            throw new RuntimeException("int must be 4 bytes");
        }
        long ret = 0;
        for (int i = 0; i < 8; i++) {
            int offset = 64 - ((i + 1) * 8);
            ret = (ret | (0xFFL & content[i]) << offset);
        }
        return ret;
    }

    public static byte[] intToBytes(int i) {
        byte[] ret = new byte[4];
        ret[0] = (byte) ((i >>> 24));
        ret[1] = (byte) ((i >>> 16));
        ret[2] = (byte) ((i >>> 8));
        ret[3] = (byte) i;
        return ret;
    }

    public static byte[] shortToBytes(short s) {
        byte[] ret = new byte[2];
        ret[0] = (byte) ((s >>> 8));
        ret[1] = (byte) s;
        return ret;
    }

    public static byte[] longToBytes(long l) {
        byte[] ret = new byte[8];
        for (int i = 0; i < 8; i++) {
            ret[i] = (byte) (l >>> (64 - ((i + 1) * 8)));
        }
        return ret;
    }

    public static boolean byteArrEquals(byte[] left, byte[] right) {
        if (left == right) {
            return true;
        }
        if (left == null || right == null) {
            return false;
        }
        if (left.length != right.length) {
            return false;
        }
        for (int i = 0; i < left.length; i++) {
            if (left[i] != right[i]) {
                return false;
            }
        }
        return true;
    }

    public static int getFileIndexByName(String fileName){
        return Integer.valueOf(fileName.substring(FILE_PREFIX.length()));
    }
}
